//
//  RewardViewController.m
//  penzer
//
//  Created by caiyc on 2018/9/23.
//  Copyright © 2018年 caiyc. All rights reserved.
//

#import "RewardViewController.h"
#import "rewordgood_Cell.h"
#import "adress_Cell.h"
#import "paytype_Cell.h"
#import "WXApi.h"
#import "Stiore_Cell.h"
#import "Store_ViewController.h"
//#import "YWAddressViewController.h"
#import "AddressListViewController.h"
@interface RewardViewController ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,strong)NSMutableArray *addressData;
@property(nonatomic,strong)NSDictionary *addressDic;
@property(nonatomic,strong)NSDictionary *storeInfo;
@property(nonatomic,strong)NSString *store_Id;
@property(assign)BOOL haveStore;

@end

@implementation RewardViewController
-(NSMutableArray *)addressData{
    if(!_addressData){
        _addressData = [NSMutableArray array];
    }
    return _addressData;
}
- (void)viewDidLoad {
    [super viewDidLoad];
      [self setNavigation:1 andTitle:@"领取奖品" andNaviColor:[UIColor whiteColor] andTitleColor:nil andRightimg:@"" andsel:nil];
     [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(paynoti:) name:@"paynoti" object:nil];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
    self.corver_View.backgroundColor = RGBA(0, 0, 0, .5);
    self.corver_View.hidden = 1;
    self.store_Id = @"";
    NSLog(@"中奖信息===%@",self.result_Order);
    [self loadAddress];
    [self loadStore];
    // Do any additional setup after loading the view from its nib.
}
-(void)loadStore{
//    if(!self.result_Order[@"goods_id"]){
//        
//    }
    NSDictionary *paramter = @{@"op":@"goods",@"ctrl":@"live",@"ac":@"store",@"ta":@"detail",@"id":self.result_Order[@"goods_id"]};
    NSLog(@"........%@",paramter);
    [self weqPostHandle:paramter success:^(id response) {
        if(response){
            if(response){
                
                if([response[@"data"][@"store_list"]isKindOfClass:[NSArray class]]){
                    self.haveStore = 1;
                    [self.tableView reloadData];
                }else{
                   self.haveStore = 0;
                     [self.tableView reloadData];
                    
                }
//                NSArray *lists = response[@"data"][@"store_list"];
//                if(lists.count>0){
//                    [self.dataSorce addObjectsFromArray:lists];
//                    [self.tableView reloadData];
//                }
            }
        }
    } failure:^(NSError *error) {
        
    }];
}
-(void)loadAddress{
    NSDictionary *params = @{@"ctrl":@"live",@"ac":@"member",@"op":@"address",@"ta":@"index"};
    [self weqPostHandle:params success:^(id response) {
        if(response){
            NSArray *datas = response[@"data"];
            if(datas.count>0){
            self.addressDic = response[@"data"][0];
            [self updateOrder];
            [self.tableView reloadData];
            }
        }else{
            
        }
    } failure:^(NSError *error) {
        
    }];
}
//更改订单地址状态
-(void)updateOrder{
    NSDictionary *params = @{@"ctrl":@"live",@"ac":@"store",@"op":@"activity",@"ta":@"up_order_address",@"address_id":self.addressDic[@"id"],@"order_id":self.order_id};
    [self weqPostHandle:params success:^(id response) {
        
    } failure:^(NSError *error) {
        
    }];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 3;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.row==0){
        rewordgood_Cell *cell = [[[NSBundle mainBundle]loadNibNamed:@"rewordgood_Cell" owner:self options:nil]lastObject];
        [cell bindData:self.result_Order];
        return cell;
    }else if (indexPath.row==1){
        adress_Cell *cell = [[[NSBundle mainBundle]loadNibNamed:@"adress_Cell" owner:self options:nil]lastObject];
        if(self.addressDic){
        [cell bindData:self.addressDic];
        }
        return cell;
    }else if (indexPath.row==2){
        
        Stiore_Cell *cell = [[[NSBundle mainBundle]loadNibNamed:@"Stiore_Cell" owner:self options:nil]lastObject];
        if(self.haveStore==1){
        if(self.storeInfo){
        cell.store_Lab.text = self.storeInfo[@"title"];
        }
            
        }else{
            [cell.imgs removeFromSuperview];
            [cell.store_Lab removeFromSuperview];
        }
        return cell;
    }
    else{
        paytype_Cell *cell = [[[NSBundle mainBundle]loadNibNamed:@"paytype_Cell" owner:self options:nil]lastObject];
        [cell bindData:self.result_Order];
        return cell;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.row==1){
        AddressListViewController *vc = [[AddressListViewController alloc]init];
        vc.needBack = 1;
        vc.selecCity=^(NSDictionary * dic){
            self.addressDic = dic;
            [self updateOrder];
            [self.tableView reloadData];
        };
        [self pushSecondVC:vc];

    }else if (indexPath.row==2){
        Store_ViewController *vc = [[Store_ViewController alloc]init];
        vc.ids = [NSString stringWithFormat:@"%@",self.result_Order[@"goods_id"]];
        __weak typeof(self)WeakSelf = self;
        vc.selctStore=^(NSDictionary * store){
            WeakSelf.storeInfo = store;
            [WeakSelf.tableView reloadData];
            WeakSelf.store_Id =[NSString stringWithFormat:@"%@", store[@"id"]];
        };
        [self pushSecondVC:vc];
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.row==0){
        return 310;
    }
    else if (indexPath.row==1){
        return 130;
    }else if (indexPath.row==2){
        if(self.haveStore==1)
        return 55;
        else return 0;
    }
    else{
        return 186;
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
//先支付
- (IBAction)pickPrize:(UIButton *)sender {
    NSDictionary *param = @{@"i":@"10",@"m":@"bz_activities",@"c":@"entry",@""@"id":self.order_id,@"op":@"pay",@"ac":@"system",@"ctrl":@"live",@"token":[XTool GetDefaultInfo:USER_INFO][@"token"],@"pay_type":@"act_live",@"store_id":self.store_Id};
    AFHTTPRequestOperationManager *manager=[AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];
   NSLog(@"请求参数%@",param);
    [manager POST:BASE_URL parameters:param success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        NSLog(@"请求结果：%@",responseObject);
        if([responseObject[@"message"][@"errno"]integerValue]==0){
                PayReq* req  = [[PayReq alloc] init];
                req.partnerId  = @"1515323121";
                req.prepayId   = responseObject[@"message"][@"message"][@"prepayid"];
                req.nonceStr  = responseObject[@"message"][@"message"][@"noncestr"];
                req.timeStamp = [responseObject[@"message"][@"message"][@"timestamp"]intValue];
                req.package = @"Sign=WXPay";
                req.sign = responseObject[@"message"][@"message"][@"sign"];
                [WXApi sendReq:req];
        }else if ([responseObject[@"message"][@"errno"]integerValue]==2){
             [WToast showWithText:@"奖品领取成功,请前往个人中心查看订单"];
            [self.navigationController popViewControllerAnimated:1];
        }
        else{
            [WToast showWithText:responseObject[@"message"][@"message"]];
            
           // [WToast showWithText:@"请求出错"];
        }
        } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
        NSLog(@"请求出错===……%@",error);
    }];

}

-(void)paynoti:(NSNotification *)no
{
    NSLog(@".....%@",no.userInfo[@"payResult"]);
    NSDictionary *payDic = no.userInfo[@"payResult"];
    if([payDic[@"resultStatus"]integerValue]==6001)
    {
        NSLog(@"用户取消支付");
    }
    if([payDic[@"resultStatus"]integerValue]==9000)
    {
        NSLog(@"用户支付成功");
        [self.navigationController popViewControllerAnimated:1];
      //  [self paySuceess];

    }
    
}


-(void)paySuceess{
    NSDictionary *params = @{@"ctrl":@"live",@"ac":@"store",@"op":@"activity",@"ta":@"pay_succ",@"id":self.order_id};
    [self weqPostHandle:params success:^(id response) {
        if(response){
            [WToast showWithText:@"支付成功，等待商家发货"];
            [self.navigationController popViewControllerAnimated:1];
    }
    } failure:^(NSError *error) {
    }];
}
- (IBAction)noprize:(id)sender {
    [self.navigationController popViewControllerAnimated:1];
   // [self.navigationController popToRootViewControllerAnimated:1];
}
@end
